//
//  MEDditStageLayer.m
//  MapEditor
//
//  Created by Eric on 3/5/12.
//  Copyright 2012 __MyCompanyName__. All rights reserved.
//

#import "MEEditStageLayer.h"
#import "BBUtil.h"
#import "MEController.h"
#import "MEDefine.h"
#import "MEUtil.h"


@implementation MEEditStageSprite
@synthesize sid;
@synthesize selected;
@synthesize prototypeParam;
@synthesize buildSprite;

@synthesize tag0;
@synthesize tag1;
@synthesize tag2;
@synthesize tag3;

-(void)dealloc{
    self.prototypeParam = nil;
    self.buildSprite = nil;
    [super dealloc];
}

+(id)sprite:(MEPrototype*)prototype
{
    MEEditStageSprite* spt = [MEEditStageSprite node];
    spt.prototypeParam = [MEPrototypeParam prototypeParamWithPrototype:prototype];    
    
    NSMutableDictionary* param = [NSMutableDictionary dictionaryWithDictionary:[prototype toDict]];
    //[param addEntriesFromDictionary:[spt toDict]];
    MESprite* build = [MESprite spriteWithDict:param];
    [spt addChild:build];  
    
    spt.buildSprite = build;
    spt.scale = spt.prototypeParam.scale;
    
    return spt;
}

+(MEEditStageSprite*)spriteWith:(NSDictionary*)param{
    MEPrototypeParam* clone = [MEPrototypeParam prototypeParamWithDict:param];
    NSInteger prototypeId = [param integerValue:@"prototype" defaultVal:0];
    clone.sid = prototypeId;
    
    CGPoint pos = NSPointToCGPoint(NSPointFromString([param objectForKey:@"pos"]));
    NSInteger sid = [param integerValue:@"sid" defaultVal:0];
    CGFloat tag0 = [param floatValue:@"tag0" defaultVal:0];
    CGFloat tag1 = [param floatValue:@"tag1" defaultVal:0];
    CGFloat tag2 = [param floatValue:@"tag2" defaultVal:0];
    CGFloat tag3 = [param floatValue:@"tag3" defaultVal:0];
    
    MEEditStageSprite* spt = [MEEditStageSprite node];
    spt.prototypeParam = clone;
    spt.positionForBody = pos;
    spt.rotation = clone.rotation;
    spt.scale = clone.scale;
    spt.tag0 = tag0;
    spt.tag1 = tag1;
    spt.tag2 = tag2;
    spt.tag3 = tag3;
    spt.sid = sid;
    
    NSMutableDictionary* cloneParam = [NSMutableDictionary dictionaryWithDictionary:[clone toDict]];
    [cloneParam addEntriesFromDictionary:[spt toDict]];
    MESprite* build = [MESprite spriteWithDict:param];
    [spt addChild:build];  
    spt.buildSprite = build;
    spt.scale = clone.scale;
    return spt;    
}

-(void)draw{
    [super draw];
    
    if (selected) {
        MESprite* spt = self.buildSprite;
        CGFloat space = 2;
        CGPoint points2[4];
        
        CGFloat w = spt.contentSize.width * spt.scaleForBody;
        CGFloat h = spt.contentSize.height * spt.scaleForBody;
        CGFloat x1 = -w/2 - space;
        CGFloat y1=  -h/2 - space;
        CGFloat x2 = x1;
        CGFloat y2 = h/2 + space;
        CGFloat x3 = w/2 + space;
        CGFloat y3 = y2;
        CGFloat x4 = x3;
        CGFloat y4 = y1;
        points2[0] = ccp(x1, y1);
        points2[1] = ccp(x2, y2);
        points2[2] = ccp(x3, y3);
        points2[3] = ccp(x4, y4);
        
        
        for (NSInteger i=0; i<4; i++) {
            points2[i] = [MEUtil rotate:points2[i] angle:CC_DEGREES_TO_RADIANS(prototypeParam.rotation) ];            
            points2[i] = ccpAdd(points2[i], spt.position);
        }
        
        
        glLineWidth(2.0f);
        //glColor4f(1, 0, 0, 1); 
        ccDrawPoly(points2, 4, YES);
        
    }
}
-(void)resetBody:(b2World*)world{
    /*
    if (isBox2dObj) {
        body = [prototype createBody:self world:world p:PTM_RATIO D:density F:friction R:restitution t:bodyType pos:self.position];
    } 
     */
    [self destroyBody];
    
    NSDictionary* param = [self toDict];
    MESprite* spt = [MESprite spriteWithDict:param];
    [spt createBody:world p:[MEScene scene].layer.ptmRatio];
    self.buildSprite = spt;
    [self addChild:spt];
}
-(void)destroyBody{
    [self.buildSprite destroyBody];
    [self.buildSprite removeFromParentAndCleanup:YES];
    self.buildSprite = nil;
}

-(NSDictionary*)toDict{
    MEPrototype* prototype = [[MEPrototypeMgr instance] prototypeWithSid:prototypeParam.sid];
    NSMutableDictionary* param = [NSMutableDictionary dictionaryWithCapacity:32];
    NSDictionary* cloneParam = [prototypeParam toDict];
    [param addEntriesFromDictionary:cloneParam];
    [param setObject:[NSNumber numberWithInteger:prototype.fileType] forKey:@"fileType"];
    [param setObject:[prototypeParam.filePath lastPathComponent] forKey:@"fileName"];
    [param setObject:[NSNumber numberWithInteger:sid] forKey:@"sid"];
    [param setObject:[NSNumber numberWithInteger:prototype.sid] forKey:@"prototype"];
    [param setObject:[NSNumber numberWithFloat:tag0] forKey:@"tag0"];
    [param setObject:[NSNumber numberWithFloat:tag1] forKey:@"tag1"];
    [param setObject:[NSNumber numberWithFloat:tag2] forKey:@"tag2"];
    [param setObject:[NSNumber numberWithFloat:tag3] forKey:@"tag3"];
    
    return param;
}


-(BOOL)isAtPos:(CGPoint)pos{
    pos = [self convertToWorldSpace:pos];
    pos = [buildSprite convertToNodeSpace:pos];
    
    MESprite *spt = buildSprite;
    CGRect bounding;
    bounding.origin = CGPointZero;
    bounding.size= spt.contentSize;
    return CGRectContainsPoint(bounding, pos);
}
-(void)setPositionForBody:(CGPoint)position{
    prototypeParam.pos = position;
    [buildSprite setPositionWithBody:position];
}
-(CGPoint)positionForBody{
    return buildSprite.position;
}

-(void)setRotation:(float)rotation{
    prototypeParam.rotation = rotation;
    [buildSprite setRotationForBody:rotation];
}

-(float)rotation{
    return prototypeParam.rotation;
}

-(void)setScale:(float)scale{
    prototypeParam.scale = scale;
    buildSprite.scaleForBody = scale;
}
-(float)scale{
    return buildSprite.scaleForBody;
}
-(void)setFlipX:(BOOL)flipX{
    prototypeParam.flipX = flipX;
    buildSprite.flipX = flipX;
}
-(void)setFlipY:(BOOL)flipY{
    prototypeParam.flipY = flipY;
    buildSprite.flipY = flipY;
}

-(NSInteger)fileType{
    MEPrototype* prototype = [[MEPrototypeMgr instance] prototypeWithSid:prototypeParam.sid];
    return prototype.fileType;
}
@end


@implementation MEEditStageSubLayer
@synthesize name;
@end

@implementation MEEditStageLayer
@synthesize stages;
@synthesize layers;
@synthesize spriteSidCount;
@synthesize zOrderCount;
@synthesize tag0;
@synthesize tag1;
@synthesize tag2;
@synthesize tag3;

@synthesize curStageIndex;
@synthesize draggedSprite;
-(void)dealloc{
    self.layers = nil;
    self.stages = nil;
    [super dealloc];
}

-(id)init{
    if (self=[super init]) {     
        self.stages = [NSMutableArray arrayWithCapacity:64];
        container = [CCNode node];
        [self addChild:container z:-1];
    }
    return self;
}


-(void)setDraggedSpriteInfo{
    MEController* ctrl = [MEController instance];
    [ctrl refreshSpriteInfo:draggedSprite];    
}

-(void)addSprite:(MEEditStageSprite*)spt{
    [[[MEController instance] selectedLayer] addChild:spt];
    [spt resetBody:world];
    
    MEEditStageSprite* last = draggedSprite;
    last.selected = NO;
    
    self.draggedSprite = spt;    
    draggedSprite.selected = YES;

    [self setDraggedSpriteInfo];
}

-(void)reorderSprite:(NSInteger)flag{
    if (!draggedSprite) {
        return;
    } 
    CCNode* parent = draggedSprite.parent;
    CCArray* children = parent.children;
    NSInteger index = [children indexOfObject:draggedSprite];
    NSInteger tgtIndex = index + flag;
    tgtIndex = MIN(children.count, MAX(0, tgtIndex));
    [children removeObjectAtIndex:index];
    [children insertObject:draggedSprite atIndex:tgtIndex];
}

-(void)addLayer{
    NSString* name = [NSString stringWithFormat:@"New Layer - %d", zOrderCount];
    [self addLayer:name];
}


-(void)addLayer:(NSString*)name{
    if (!layers) {
        self.layers = [NSMutableArray arrayWithCapacity:64];
    }
    MEEditStageSubLayer *layer = [MEEditStageSubLayer node];
    layer.name = name;
    [container addChild:layer z:zOrderCount++];
    
    [layers addObject:layer];
}


-(BOOL)removeLayer:(CCLayer*)layer{
    if (layers) {
        [layer removeFromParentAndCleanup:YES];
        [layers removeObject:layer]; 
        return YES;
    }

    return NO;
}

-(NSInteger)moveLayer:(CCLayer*)layer way:(NSInteger)way{
    NSInteger index = [layers indexOfObject:layer];
    NSInteger tgtIndex = index + way;
    if (index==0 || tgtIndex==0||tgtIndex>=[layers count]) {
        return index;
    }
    [layers removeObject:layer];
    [layers insertObject:layer atIndex:tgtIndex];
    [container removeAllChildrenWithCleanup:YES];
    zOrderCount = 0;
    for (CCLayer* layer in layers) {
        [container addChild:layer z:zOrderCount ++];
    }
    return tgtIndex;
}


-(void)addJoint{
    
}



-(void)addStage{
    NSMutableDictionary* stage = [NSMutableDictionary dictionaryWithCapacity:64];
    NSMutableArray* stageLayers = [NSMutableArray arrayWithCapacity:64];
    [stage setObject:stageLayers forKey:@"layers"];
    [stage setObject:[NSNumber numberWithInteger:0] forKey:@"zOrderCount"];
    [stage setObject:[NSNumber numberWithInteger:0] forKey:@"spriteSidCount"];
    [stage setObject:[NSNumber numberWithInteger:tag0] forKey:@"tag0"];
    [stage setObject:[NSNumber numberWithInteger:tag1] forKey:@"tag1"];
    [stage setObject:[NSNumber numberWithInteger:tag2] forKey:@"tag2"];
    [stage setObject:[NSNumber numberWithInteger:tag3] forKey:@"tag3"];
    
    [stage setObject:[NSNumber numberWithFloat:PTM_RATIO] forKey:@"ptmRatio"];
    [stage setObject:[NSString stringWithFormat:@"{x=%f;y=%f}", GRATIVE_DLF_X, GRATIVE_DLF_Y] forKey:@"gravity"];
    
    if ([layers count]>0) {
        for (MEEditStageSubLayer* subLayer in layers) {
            MEEditStageSubLayer *layer = [MEEditStageSubLayer node];
            layer.name = subLayer.name;        
            [stageLayers addObject:layer];
        }

    }else{
        MEEditStageSubLayer *Background = [MEEditStageSubLayer node];
        Background.name = @"Background";   
        [stageLayers addObject:Background];
        MEEditStageSubLayer *Sprites = [MEEditStageSubLayer node];
        Sprites.name = @"Sprites";   
        [stageLayers addObject:Sprites];
    }
    
    
    [stages addObject:stage];
}
-(void)removeStage:(NSInteger)stageIndex{
    [stages removeObjectAtIndex:stageIndex];
}

-(void)changeStage:(NSInteger)stageIndex{
    MEController* ctrl = [MEController instance];
    if (curStageIndex<[stages count]&&stageIndex!=curStageIndex) {
        NSMutableDictionary* stage = [stages objectAtIndex:curStageIndex];
        [stage setObject:layers forKey:@"layers"];
        [stage setObject:[NSNumber numberWithInteger:zOrderCount] forKey:@"zOrderCount"];
        [stage setObject:[NSNumber numberWithInteger:spriteSidCount] forKey:@"spriteSidCount"];
        [stage setObject:[NSNumber numberWithInteger:tag0] forKey:@"tag0"];
        [stage setObject:[NSNumber numberWithInteger:tag1] forKey:@"tag1"];
        [stage setObject:[NSNumber numberWithInteger:tag2] forKey:@"tag2"];
        [stage setObject:[NSNumber numberWithInteger:tag3] forKey:@"tag3"];
        
        
        NSIndexSet* index = ctrl.layersPane.selectionIndexes;
        [stage setObject:index forKey:@"index"];
        
        [stage setObject:[NSNumber numberWithFloat:ptmRatio] forKey:@"ptmRatio"];
        [stage setObject:[NSString stringWithFormat:@"{x=%f;y=%f}", grative.x, grative.y] forKey:@"gravity"];
    }
    curStageIndex = stageIndex;
    
    for (CCLayer* layer in layers) {     
        for (MEEditStageSprite* spt in layer.children) {
            [spt destroyBody];
        }
    }
    for (CCLayer* layer in layers) {
        [layer removeFromParentAndCleanup:YES];
    }
    
    NSDictionary* curStage = [stages objectAtIndex:curStageIndex];
    self.layers = [curStage objectForKey:@"layers"];
    self.zOrderCount = [curStage integerValue:@"zOrderCount" defaultVal:0];
    self.spriteSidCount = [curStage integerValue:@"spriteSidCount" defaultVal:0];
    self.tag0 = [curStage floatValue:@"tag0" defaultVal:0];
    self.tag1 = [curStage floatValue:@"tag1" defaultVal:0];
    self.tag2 = [curStage floatValue:@"tag2" defaultVal:0];
    self.tag3 = [curStage floatValue:@"tag3" defaultVal:0];
    
    
    [ctrl.layersPane setContent:layers];
    NSIndexSet* index = [curStage objectForKey:@"index"];
    if (!index) {
        index = [NSIndexSet indexSetWithIndex:0];
    }
    [ctrl.layersPane setSelectionIndexes:index];   
    
    
    CGFloat pr = [curStage floatValue:@"ptmRatio" defaultVal:PTM_RATIO];
    CGPoint gr = NSPointToCGPoint(NSPointFromString([curStage objectForKey:@"gravity"]));
    [self resetWorld:pr gravityX:gr.x gravityY:gr.y];
    
    NSInteger z = zOrderCount;
    for (CCLayer* layer in layers) {
        [container addChild:layer z:z++];
    }
}


-(void)moveStage:(NSInteger)stageIndex tgt:(NSInteger)tgtIndex{
    NSDictionary* stage1 = [NSMutableDictionary dictionaryWithDictionary: [stages objectAtIndex:stageIndex]];
    [stages removeObjectAtIndex:stageIndex];
    [stages insertObject:stage1 atIndex:tgtIndex];
    curStageIndex = tgtIndex;
}




-(void)resetWorld:(CGFloat)ptm gravityX:(CGFloat)gx gravityY:(CGFloat)gy{
    for (CCLayer* layer in layers) {     
        for (MEEditStageSprite* spt in layer.children) {
            [spt destroyBody];
        }
    }
    [super resetWorld:ptm gravityX:gx gravityY:gy];
    if (curStageIndex<[stages count]) {
        MEController* ctrl = [MEController instance];
        NSMutableDictionary* stage = [stages objectAtIndex:curStageIndex];
        [stage setObject:layers forKey:@"layers"];
        [stage setObject:[NSNumber numberWithInteger:zOrderCount] forKey:@"zOrderCount"];
        [stage setObject:[NSNumber numberWithInteger:spriteSidCount] forKey:@"spriteSidCount"];
        [stage setObject:[NSNumber numberWithInteger:tag0] forKey:@"tag0"];
        [stage setObject:[NSNumber numberWithInteger:tag1] forKey:@"tag1"];
        [stage setObject:[NSNumber numberWithInteger:tag2] forKey:@"tag2"];
        [stage setObject:[NSNumber numberWithInteger:tag3] forKey:@"tag3"];
        
        NSIndexSet* index = ctrl.layersPane.selectionIndexes;
        [stage setObject:index forKey:@"index"];
        
        [stage setObject:[NSNumber numberWithFloat:ptmRatio] forKey:@"ptmRatio"];
        [stage setObject:[NSString stringWithFormat:@"{x=%f;y=%f}", grative.x, grative.y] forKey:@"gravity"];

    }
    for (CCLayer* layer in layers) {     
        for (MEEditStageSprite* spt in layer.children) {
            [spt resetBody:world];
        }
    }
}
/*
-(NSArray*)toExportParam{
    NSMutableArray* stagesParam = [NSMutableArray arrayWithCapacity:[stages count]];
    for (NSDictionary* stage in stages) {
        NSMutableDictionary* stageParam = [NSMutableDictionary dictionaryWithCapacity:[stage count]];
        
        NSArray* subLayers = [stage objectForKey:@"layers"];
        NSMutableArray* subLayerParams = [NSMutableArray arrayWithCapacity:[subLayers count]]; 
        for (MEEditStageSubLayer* layer in subLayers) {
            NSMutableArray* spts = [NSMutableArray arrayWithCapacity:[layer.children count]];
            for (MEEditStageSprite* spt in layer.children) {
                NSDictionary* sptParam = [spt toExportDict];
                [spts addObject:sptParam];
            }
            NSMutableDictionary* layerParam = [NSMutableDictionary dictionaryWithCapacity:2];
            [layerParam setObject:layer.name forKey:@"name"];
            [layerParam setObject:spts forKey:@"sprites"];
            [subLayerParams addObject:layerParam];
        }
        NSPoint g = NSPointFromString([stage objectForKey:@"gravity"]);
        [stageParam setObject:subLayerParams forKey:@"layers"];
        [stageParam setObject:[stage objectForKey:@"zOrderCount"] forKey:@"zOrderCount"];
        [stageParam setObject:[stage objectForKey:@"spriteSidCount"] forKey:@"spriteSidCount"];
        [stageParam setObject:[stage objectForKey:@"tag0"] forKey:@"tag0"];
        [stageParam setObject:[stage objectForKey:@"tag1"] forKey:@"tag1"];
        [stageParam setObject:[stage objectForKey:@"tag2"] forKey:@"tag2"];
        [stageParam setObject:[stage objectForKey:@"tag3"] forKey:@"tag3"];
        
        
        [stageParam setObject:[stage objectForKey:@"ptmRatio"] forKey:@"ptmRatio"];
        [stageParam setObject:[NSString stringWithFormat:@"{%f,%f}",g.x,g.y] forKey:@"gravity"];
        
        [stagesParam addObject:stageParam];
    }
    return stagesParam;
}
 */
 
-(NSArray*)toParam{ 
    NSMutableDictionary* stage = [stages objectAtIndex:curStageIndex];
    [stage setObject:layers forKey:@"layers"];
    [stage setObject:[NSNumber numberWithInteger:zOrderCount] forKey:@"zOrderCount"];
    [stage setObject:[NSNumber numberWithInteger:spriteSidCount] forKey:@"spriteSidCount"];
    [stage setObject:[NSNumber numberWithFloat:tag0] forKey:@"tag0"];
    [stage setObject:[NSNumber numberWithFloat:tag1] forKey:@"tag1"];
    [stage setObject:[NSNumber numberWithFloat:tag2] forKey:@"tag2"];
    [stage setObject:[NSNumber numberWithFloat:tag3] forKey:@"tag3"];
    
    MEController* ctrl = [MEController instance];
    NSIndexSet* index = ctrl.layersPane.selectionIndexes;
    [stage setObject:index forKey:@"index"];    
    [stage setObject:[NSNumber numberWithFloat:ptmRatio] forKey:@"ptmRatio"];
    [stage setObject:[NSString stringWithFormat:@"{x=%f;y=%f}", grative.x, grative.y] forKey:@"gravity"];
    
    
    NSMutableArray* stagesParam = [NSMutableArray arrayWithCapacity:[stages count]];
    for (NSDictionary* stage in stages) {
        NSMutableDictionary* stageParam = [NSMutableDictionary dictionaryWithCapacity:[stage count]];
        
        NSArray* subLayers = [stage objectForKey:@"layers"];
        NSMutableArray* subLayerParams = [NSMutableArray arrayWithCapacity:[subLayers count]]; 
        for (MEEditStageSubLayer* layer in subLayers) {
            NSMutableArray* spts = [NSMutableArray arrayWithCapacity:[layer.children count]];
            for (MEEditStageSprite* spt in layer.children) {
                NSDictionary* sptParam = [spt toDict];
                [spts addObject:sptParam];
            }
            NSMutableDictionary* layerParam = [NSMutableDictionary dictionaryWithCapacity:2];
            [layerParam setObject:layer.name forKey:@"name"];
            [layerParam setObject:spts forKey:@"sprites"];
            [subLayerParams addObject:layerParam];
        }
        [stageParam setObject:subLayerParams forKey:@"layers"];
        [stageParam setObject:[stage objectForKey:@"zOrderCount"] forKey:@"zOrderCount"];
        [stageParam setObject:[stage objectForKey:@"spriteSidCount"] forKey:@"spriteSidCount"];
        [stageParam setObject:[stage objectForKey:@"tag0"] forKey:@"tag0"];
        [stageParam setObject:[stage objectForKey:@"tag1"] forKey:@"tag1"];
        [stageParam setObject:[stage objectForKey:@"tag2"] forKey:@"tag2"];
        [stageParam setObject:[stage objectForKey:@"tag3"] forKey:@"tag3"];
        
        [stageParam setObject:[stage objectForKey:@"ptmRatio"] forKey:@"ptmRatio"];
        [stageParam setObject:[stage objectForKey:@"gravity"] forKey:@"gravity"];
        
        [stagesParam addObject:stageParam];
    }
    return stagesParam;
}
-(void)loadDict:(NSDictionary*)stagesParam{
    [stages removeAllObjects];
    
    
    for (NSDictionary* stageParam in stagesParam) {
        NSMutableDictionary* stage = [NSMutableDictionary dictionaryWithCapacity:[stageParam count]];
        
        NSArray* subLayersParam = [stageParam objectForKey:@"layers"];
        NSMutableArray* subLayers = [NSMutableArray arrayWithCapacity:[subLayersParam count]];
        
        for (NSDictionary* layerParam in subLayersParam) {
            NSString* layerName = [layerParam objectForKey:@"name"];
            MEEditStageSubLayer *layer = [MEEditStageSubLayer node];
            layer.name = layerName;
            [subLayers addObject:layer];
            
            NSArray* sptParams = [layerParam objectForKey:@"sprites"];
            for (NSDictionary* sptParam in sptParams) {
                MEEditStageSprite* spt = [MEEditStageSprite spriteWith:sptParam];
                [layer addChild:spt];
            }
        }
        
        [stage setObject:subLayers forKey:@"layers"];
        [stage setObject:[stageParam objectForKey:@"zOrderCount"]  forKey:@"zOrderCount"];  
        [stage setObject:[stageParam objectForKey:@"spriteSidCount"]  forKey:@"spriteSidCount"];  
        [stage setObject:[stageParam objectForKey:@"tag0"] forKey:@"tag0"];
        [stage setObject:[stageParam objectForKey:@"tag1"] forKey:@"tag1"];
        [stage setObject:[stageParam objectForKey:@"tag2"] forKey:@"tag2"];
        [stage setObject:[stageParam objectForKey:@"tag3"] forKey:@"tag3"];
        
        [stage setObject:[stageParam objectForKey:@"ptmRatio"]  forKey:@"ptmRatio"];   
        [stage setObject:[stageParam objectForKey:@"gravity"]  forKey:@"gravity"];   
        
        [stages addObject:stage];
    }
    if ([stages count]>0) {
        [self changeStage:0];
    } 
}

-(MEEditStageSprite*)getSpriteAt:(CGPoint)p{  
    CCLayer *layer =  [[MEController instance] selectedLayer];
    if (layer.children) {
        CCArray* reverseAry = [CCArray arrayWithArray:layer.children];
        [reverseAry reverseObjects];
        for (MEEditStageSprite* node in reverseAry) {
            CGPoint tmpp = [node convertToNodeSpace:p];
            if ([node isAtPos:tmpp]) {
                return node;
            }
        } 
    }  
    
    return nil;
}


-(BOOL) mouseDown:(NSEvent *)event
{
    MEEditStageSprite* last = draggedSprite;
    last.selected = NO;
    CGPoint p = [[CCDirector sharedDirector] convertEventToGL:event];
    self.draggedSprite = [self getSpriteAt:p];
    
    [self setDraggedSpriteInfo];
    
    if (!draggedSprite) {
        return NO;
    }
    draggedSprite.selected = YES;
    prePoint = p;
    
    return YES;	
}
-(BOOL) mouseDragged:(NSEvent *)event
{
    CGPoint p = [(CCDirectorMac*)[CCDirector sharedDirector] convertEventToGL:event];
    CGPoint moveBy = ccpSub(p, prePoint);
    moveBy.x /= self.scale;
    moveBy.y /= self.scale;
    
    prePoint = p;
    draggedSprite.positionForBody = ccpAdd(draggedSprite.positionForBody, moveBy);
    [self setDraggedSpriteInfo];
    return YES;
}
-(void)rightClick:(NSEvent *)event{
    CGPoint p = [(CCDirectorMac*)[CCDirector sharedDirector] convertEventToGL:event];
    CCNode* sprite = [self getSpriteAt:p];
    if (!sprite) {
        return;
    }
    
    NSMenu* rightClick =  [ [NSMenu alloc] initWithTitle:@"RightClick"];
    
    //Add NSMenuItem(s) to the rightClick NSMenu
    NSMenuItem* remove = [[[NSMenuItem  alloc] init] autorelease];
    [remove setTitle:@"Remove"];
    [remove setRepresentedObject:sprite];
    [remove setAction:@selector(remove:)];
    [remove setTarget:self];
    [rightClick addItem:remove];
    
    [NSMenu popUpContextMenu:rightClick withEvent:event forView:[MEController instance].glView];
}

-(void)remove:(id)obj{
    //NSLog(@"removeSprite:obj=%@", [obj representedObject]); 
    //[[obj representedObject] removeFromParentAndCleanup:YES];
    MEEditStageSprite* spt = [obj representedObject];
    [self removeSprite:spt];
}
-(void)removeSprite:(MEEditStageSprite*)spt{
    [spt destroyBody];
    [spt removeFromParentAndCleanup:YES];
    
    if (spt==draggedSprite) {
        self.draggedSprite = nil;
    }
}
@end

